import * as crypto from 'crypto';
const path = require('path');
const moment = require("moment");
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
const {AGCClient, CredentialParser} = require("@hw-agconnect/common-server");
// import { user } from './db/user'
// import {template_list} from './db/template_list'
const user = require('./db/user')
// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientCN", "CN");
const agcClient = AGCClient.getInstance("clientCN");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);
//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

function generateRandomNumber() {
  let randomNum = Math.floor(Math.random() * 1000000);
  return randomNum.toString().padStart(6, '0');
}

let myHandler = async function (event, context, callback, logger) {
  const { uid, name, avatarUrl, bgWallUrl, sex, signature, phone } = event.body ? JSON.parse(event.body) : event
  // 如果id都沒有，则新增数据
  const bookInfo = new user.user();
  bookInfo.setId(uid);
  const operator = clouddb.CloudDBZoneObjectOperator.build(bookInfo)
  const bookInfoJson = {
    name,
    avatarUrl,
    bgWallUrl,
    sex,
    signature
  }
  if (phone) {
    bookInfoJson['phone'] = phone
  }
  // operator.update('userId', );
  for (const key in bookInfoJson) {
    if (![undefined, null].includes(bookInfoJson[key])) {
      operator.update(key, bookInfoJson[key]);
    }
  }
  operator.update('updateTime', moment().format("YYYY/MM/DD HH:mm:ss"));
  await mCloudDBZone.executeUpdate(operator)
  let res = new context.HTTPResponse({
    code: 200,
    msg: '成功',
    data: {}
  }, {
    "faas-content-type": "json"
  }, "application/json", "200");
  callback(res);
};

export { myHandler }
